package com.xuelang.pipeline.domain.resource.service.impl;

import com.xuelang.pipeline.client.common.exception.BizException;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.resource.dto.EnvironmentQuery;
import com.xuelang.pipeline.domain.resource.Environment;
import com.xuelang.pipeline.domain.resource.repository.EnvironmentRepository;
import com.xuelang.pipeline.domain.resource.service.EnvironmentDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 环境领域服务实现类
 *
 * @author xiwen.zxg
 * @since 2024/5/15
 */
@Service
public class EnvironmentDomainServiceImpl implements EnvironmentDomainService {

    @Autowired
    private EnvironmentRepository environmentRepository;

    @Override
    public PageRecord<Environment> pageList(long currentPage, long pageSize, EnvironmentQuery environmentQuery) {
        return environmentRepository.pageList(currentPage, pageSize, environmentQuery);
    }

    @Override
    public List<Environment> list(EnvironmentQuery environmentQuery) {
        return environmentRepository.list(environmentQuery);
    }


    @Override
    public Boolean save(Environment environment) {
         if(existsCode(environment.getApplicationCode(), environment.getCode())) {
            throw new BizException("环境编码已经存在");
        }
        if(existsName(environment.getApplicationCode(), environment.getCode(), environment.getName())) {
            throw new BizException("环境名称已经存在");
        }
        return environmentRepository.save(environment);
    }

    @Override
    public Boolean update(Environment environment) {
         // 更新时，名称不能重复，摒弃当前环境的名称。
        if(existsName(environment.getApplicationCode(), environment.getCode(), environment.getName())) {
            throw new BizException("环境名称已经存在");
        }
        return environmentRepository.update(environment);
    }

    @Override
    public Boolean delete(String uuid) {
        return environmentRepository.delete(uuid);
    }

    @Override
    public Environment query(String uuid) {
        return environmentRepository.query(uuid);
    }

    @Override
    public Boolean existsEnvironmentBySpaceUuid(String spaceUuid) {
        return environmentRepository.existsEnvironmentBySpaceUuid(spaceUuid);
    }

    @Override
    public Boolean deleteByApplicationCode(String applicationCode) {
        return environmentRepository.deleteByApplicationCode(applicationCode);
    }

    @Override
    public Boolean existsCode(String applicationCode, String environmentCode) {
        return environmentRepository.existsCode(applicationCode, environmentCode);
    }

    @Override
    public Boolean existsName(String applicationCode, String environmentCode, String environmentName) {
        return environmentRepository.existsName(applicationCode, environmentCode, environmentName);
    }
}
